/**
 * 
 */
package net.sf.cldsql.dj.utl;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;


/**
 * DiConf
 */
public class DiConf {

    /** conn pools */
    public static final String SQL_POOLS = "sql.pools";
    
    /** default conn pool */
    public static final String SQL_POOL_DEFAULT = "sql.pool_default";
    
    /** jdbc.dbms const */
    public static final String JDBC_DBMS = "dbms";

    /** jdbc.driver const */
    public static final String JDBC_DRIVER = "driver";

    /** jdbc.url const */
    public static final String JDBC_URL = "url";

    /** jdbc.username const */
    public static final String JDBC_USERNAME = "username";

    /** jdbc.password const */
    public static final String JDBC_PASSWORD = "password";

    /** jdbc.max_conn */
    public static final String MAX_CONN = "max_conn";

    /** jdbc.rset_naming_style */
    public static final String JDBC_RSET_NAMING_STYLE = "rset_naming_style";
    
    /** jdbc.rset_name_style=java */
    public static final String JDBC_RSET_NAMING_STYLE_JAVA = "java";

    public static final String JDBC_AUTO_COMMIT = "auto_commit";

    public static final String JDBC_AUTO_COMMIT_TRUE = "true";

    public static final String MAX_RETRIES = "max_retries";
    
    /** internal storage */
    private final Properties prop = new Properties();
    
    /**
     * init config
     * @param configFilename
     */
    public DiConf(String configFilename) {
        if (configFilename.endsWith("properties")) {
            try {
                prop.load(new FileInputStream(configFilename));
            } catch (IOException e) {
                throw new DiException(e);
            }
        } else {
            throw new DiException("Unknow config file " + configFilename);
        }
    }
    
    /**
     * get config value with key
     * @param key config key
     * @return config value
     */
    public String get(String key) {
        Object ret = prop.get(key);
        return ret == null ? null : ret instanceof String ? (String)ret : ret.toString();
    }

    /**
     * @param section
     * @param key
     * @return
     */
    public String get(String section, String key) {
        return get(section + "." + key);
    }
    
    public List<String> getKeys(String section) {
        List<String> ret = new ArrayList<String>();
        for (Object key : prop.keySet()) {
            XfixParser xfix = new XfixParser(XfixParser.PREFIX, ".");
            if (xfix.parse((String)key, section)) {
                ret.add(xfix.getOtherPart());
            }
        }
        return ret;
    }
    
}
